package com.shell.guard.security.filter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;

import com.shell.guard.utils.HttpUtil;

public class CustomLogoutHandler implements LogoutHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(CustomLogoutHandler.class);
	@Autowired
	private TokenStore tokenStore;

	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		Assert.notNull(this.tokenStore, "tokenStore must be set");
		Cookie[] cookies = request.getCookies();
		String token = null;
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("access_token")) {
					token = cookie.getValue();
					break;
				}
			}
		}
		Assert.hasText(token, "token must be set");
		if (isJwtBearerToken(token)) {
			token = token.substring(6);
			OAuth2AccessToken existingAccessToken = this.tokenStore.readAccessToken(token);
			if (existingAccessToken != null) {
				if (existingAccessToken.getRefreshToken() != null) {
					LOGGER.info("remove refreshToken!", existingAccessToken.getRefreshToken());
					OAuth2RefreshToken refreshToken = existingAccessToken.getRefreshToken();
					this.tokenStore.removeRefreshToken(refreshToken);
				}
				LOGGER.info("remove existingAccessToken!", existingAccessToken);
				this.tokenStore.removeAccessToken(existingAccessToken);
			}
			Cookie killMyCookie = new Cookie("access_token", null);
			killMyCookie.setMaxAge(0);
			killMyCookie.setPath("/");
			response.addCookie(killMyCookie);
			HttpUtil.retMsgNotLoggedIn(response);
			return;
		}
		throw new BadClientCredentialsException();
	}

	private boolean isJwtBearerToken(String token) {
		return (StringUtils.countMatches(token, ".") == 2)
				&& ((token.startsWith("Bearer")) || (token.startsWith("bearer")));
	}
}